package com.qingcheng.service.pay;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.wxpay.sdk.Config;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingcheng.pojo.order.Order;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Welcome to the most Amazing IntelliJ IIIDEA.
 * Creat0r: ^_^ fffantianxing ^_^
 * Date: 2019-07-21
 * Time: 16:05
 */
@Service
public class WeiXinPayServiceImpl implements WeiXinPayService {

    @Autowired
    private Config config;
    @Autowired
    private OrderService orderService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Reference
    private SkuService skuService;

    /**
     * 生成微信支付二维码
     *
     * @param orderId
     * @param money
     * @param notifyUrl
     * @return
     */
    @Override
    public Map<String, String> createNative(String orderId, Integer money, String notifyUrl) {


        try {
            //封装请求参数
            Map<String, String> map = new HashMap<>();
            map.put("appid", config.getAppID());//公众账号ID
            map.put("mch_id", config.getMchID());//mch_id
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            map.put("body", "青橙");//商品描述
            map.put("out_trade_no", orderId);//商户订单号
            map.put("total_fee", money + "");//标价金额
            map.put("spbill_create_ip", "127.0.0.1");//终端IP
            map.put("notify_url", notifyUrl);//通知地址
            map.put("trade_type", "NATIVE");//交易类型

            //xml类型的参数
            String xmlString = WXPayUtil.generateSignedXml(map, config.getKey());
            System.out.println("request param is " + xmlString);

            //发送请求
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String result = wxPayRequest.requestWithCert("/pay/unifiedorder", null, xmlString, false);

            System.out.println("result is " + result);


            //解析xml数据
            Map<String, String> resultMap = WXPayUtil.xmlToMap(result);
            String code_url = resultMap.get("code_url");
            System.out.println(code_url);
            Map returnMap = new HashMap();
            returnMap.put("code_url", resultMap.get("code_url"));
            returnMap.put("out_trade_no", orderId);
            returnMap.put("total_fee", money + "");
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap();
        }

    }

    @Override
    public void notifyLogic(String xml) {
        try {
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            boolean signatureValid = WXPayUtil.isSignatureValid(map, config.getKey());
            System.out.println("验证签名是否正确：" + signatureValid);
            if (signatureValid) {
                if ("SUCCESS".equals(map.get("result_code"))) {
                    orderService.updateOrderStatus(map.get("out_trade_no"), map.get("transaction_id"));
                    rabbitTemplate.convertAndSend("pay.notify", "", map.get("out_trade_no"));
                } else {
                    System.out.println("支付失败");
                }
            } else {
                System.out.println("签名验证异常");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询订单支付状态
     * @param out_trade_no
     * @return
     */
    @Override
    public boolean checkPayStatus(String out_trade_no) {

        try {
            //封装参数
            Map map = new HashMap();
            map.put("appid", config.getAppID());//公众账号ID
            map.put("mch_id", config.getMchID());//mch_id
            map.put("out_trade_no", out_trade_no);//商品订单号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            String xmlString = WXPayUtil.generateSignedXml(map, config.getKey());
            System.out.println("请求参数是：" + xmlString);

            //发送请求
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String resultXml = wxPayRequest.requestWithCert("/pay/orderquery", "", xmlString, false);
            System.out.println("查询结果是：" + resultXml);

            //将结果转换成map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
            String payResult = resultMap.get("result_code");
            Order order = orderService.findById(out_trade_no);
            if ("SUCCESS".equals(payResult) && payResult != "") {//查询结果为SUCCESS是支付成功
                if (order!=null&&order.getPayStatus().equals("0")){//如果订单还是未支付状态，修改订单状态
                    order.setPayStatus("1");//设置支付状态
                    order.setUpdateTime(new Date());//设置更新时间
                    order.setPayTime(new Date());//设置支付时间
                    order.setPayType("1");
                    orderService.update(order);
                }
                return true;
            } else {
                closeOrder(out_trade_no);//关闭微信支付订单
                //关闭订单
                order.setCloseTime(new Date());//设置订单关闭时间
                order.setOrderStatus("2");//关闭订单
                order.setUpdateTime(new Date());//设置更新时间

                orderService.update(order);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    @Override
    public void closeOrder(String out_trade_no) {

        try {
            //封装参数
            Map map = new HashMap();
            map.put("appid", config.getAppID());//公众账号ID
            map.put("mch_id", config.getMchID());//mch_id
            map.put("out_trade_no", out_trade_no);//微信订单号
            map.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            String xmlString = null;
            xmlString = WXPayUtil.generateSignedXml(map, config.getKey());
            System.out.println("请求参数是：" + xmlString);

            //发送请求
            WXPayRequest wxPayRequest = new WXPayRequest(config);
            String resultXml = wxPayRequest.requestWithCert("/pay/closeorder", "", xmlString, false);

            System.out.println(resultXml);
            //转换成map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
            String return_code = resultMap.get("return_code");
            if ("SUCCESS".equals(return_code)&&""!=return_code){
                System.out.println("订单取消成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
